package code.command {

import code.Model;
import code.event.InsertVoteEvent;
import code.remote.ResultErrorContainer;
import code.remote.ResultErrorReceivedEvent;
import code.remote.request.InsertVoteRequest;
import code.vo.Topic;

import com.adobe.cairngorm.commands.ICommand;
import com.adobe.cairngorm.control.CairngormEvent;

import logging.Logger;

import mx.controls.Alert;

public class InsertVoteCommand implements ICommand {
	
	private static const LOG: Logger = Logger.getLogger("code.command.InsertVoteCommand");
	
	private var _topic: Topic;
	
	public function InsertVoteCommand() {
	}

	public function execute(_event: CairngormEvent): void {
		const event: InsertVoteEvent = _event as InsertVoteEvent;
		LOG.fine("Executing insert vote [event="+event+"].");
		
		_topic = event.topic;
		if(_topic.yetVoted == true) {
			throw new Error("_topic.yetVoted == true");
		}
		
		_topic.isVotingInProgress = true;
		const req: InsertVoteRequest = new InsertVoteRequest(Model.instance.currentUser, _topic);
		req.addEventListener(ResultErrorReceivedEvent.RESULT_ERROR_RECEIVED, onResultReceived);
		req.doSend();
	}
	
	private function onResultReceived(event: ResultErrorReceivedEvent): void {
		const err: ResultErrorContainer = event.errorContainer;
		
		if(err.errorCode == 0) {
			// avoid full data refresh by manipulating local data only
			_topic.yetVoted = true;
			_topic.voteCnt++;
			Model.instance.recheckMaxVoteCount();
			
			Alert.show("You voted for '" + _topic.title + "'.", "Vote Saved");
		} else {
			Alert.show(err.errorMessage, "Vote Error");
		}
		
		_topic.isVotingInProgress = false;
	}
	
}
}